from typing import List, Tuple, Optional
from sqlalchemy.orm import Session
from sqlalchemy import or_, and_
from app.models.question import Question
from app.schemas.question import QuestionCreate, QuestionUpdate, QuestionFilter

def get_question(db: Session, question_id: int) -> Optional[Question]:
    """
    获取单个题目
    """
    return db.query(Question).filter(Question.id == question_id).first()

def get_questions(
    db: Session,
    filter_params: QuestionFilter
) -> Tuple[List[Question], int]:
    """
    获取题目列表，支持多种过滤条件
    """
    query = db.query(Question)
    
    # 应用过滤条件
    if filter_params.type:
        query = query.filter(Question.type == filter_params.type)
    if filter_params.difficulty:
        query = query.filter(Question.difficulty == filter_params.difficulty)
    if filter_params.topic:
        query = query.filter(Question.topic == filter_params.topic)
    if filter_params.status:
        query = query.filter(Question.status == filter_params.status)
    if filter_params.tags:
        query = query.filter(Question.tags.overlap(filter_params.tags))
    if filter_params.search:
        search = f"%{filter_params.search}%"
        query = query.filter(
            (Question.title.ilike(search)) |
            (Question.content.ilike(search))
        )
    
    # 计算总数
    total = query.count()
    
    # 分页
    query = query.offset((filter_params.page - 1) * filter_params.page_size)
    query = query.limit(filter_params.page_size)
    
    return query.all(), total

def create_question(db: Session, question_in: QuestionCreate) -> Question:
    """
    创建新题目
    """
    question_data = question_in.dict()
    if not question_data.get('status'):
        question_data['status'] = 'approved'
    
    question = Question(**question_data)
    db.add(question)
    db.commit()
    db.refresh(question)
    return question

def update_question(
    db: Session,
    question_id: int,
    question_in: QuestionUpdate
) -> Optional[Question]:
    """
    更新题目
    """
    question = get_question(db, question_id)
    if not question:
        return None
    
    update_data = question_in.dict(exclude_unset=True)
    for field, value in update_data.items():
        setattr(question, field, value)
    
    db.add(question)
    db.commit()
    db.refresh(question)
    return question

def delete_question(db: Session, question_id: int) -> bool:
    """
    删除题目
    """
    question = get_question(db, question_id)
    if not question:
        return False
    
    db.delete(question)
    db.commit()
    return True

def bulk_create_questions(
    db: Session,
    questions: List[QuestionCreate]
) -> List[Question]:
    """
    批量创建题目
    """
    db_questions = []
    for question in questions:
        question_data = question.dict()
        if not question_data.get('status'):
            question_data['status'] = 'approved'
        db_questions.append(Question(**question_data))
    
    db.add_all(db_questions)
    db.commit()
    for question in db_questions:
        db.refresh(question)
    return db_questions 